<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/15
 * Time: 22:19
 */

namespace app\api\until;

use EasyWeChat\Foundation\Application;
use app\api\model\WeUsers;

class WeChat
{
    protected $code;
    protected $msg;
    protected $data = [];
    protected $mini_program;
    protected $session_key;
    protected $open_id;
    protected $union_id;

    function start()
    {
        $options = [
            'debug' => true,
            'mini_program.app_id' => 'wx166522815b2b7bba',
            'mini_program.secret' => '519553b3dad7267cb5b0751a22134cfc',
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            // ...
        ];

        $this->mini_program = new Application($options);
//        $data  = $this->mini_program->mini_program->sns->getSessionKey();
//        $data->toArray()
        return $this;
    }

    /**
     * 获取session_key open_id union_id
     * @param $code
     * @return $this|void
     */
    public function getSessionKey($code)
    {
        $data = $this->mini_program->mini_program->sns->getSessionKey($code)->toArray();
        if (isset($data['errcode'])) {
            list($this->code, $this->msg) = [0, '无效code'];
            return;
        }
        list($this->session_key, $this->open_id, $this->union_id) = [$data['session_key'], $data['openid'], isset($data['union_id']) ? $data['union_id'] : ''];
        return $this;
    }

    /**
     * 验证同一微信用户
     * @param $rawData
     * @param $signature
     * @return bool
     */
    public function verify($rawData, $signature)
    {
        $session_key = &$this->session_key;
        $str = $rawData.$session_key;
        $en_code = sha1($str);
        if ($en_code === $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户信息
     * @param $rwaData
     * @return mixed
     */
    public function getUserInfo($rwaData)
    {
        $data = json_decode($rwaData, true);
        $data['union_id'] = $this->union_id ? $this->union_id : '';//给union_id一个默认值 在没有返回union_id得情况下
        $data['open_id'] = $this->open_id;
        return $data;
    }
}